<?php


namespace app\backend\services;

use App\backend\models\BigWheelLogModel;
use App\backend\models\BigWheelModel;
use App\backend\models\BigWheelPrizeModel;
use App\backend\models\GoodsModel;
use App\backend\services\lottery\LotteryServices;
use App\common\models\Coupon;
use App\common\services\BaseServices;
use App\common\models\Member;



class BigWheelServices extends BaseServices
{

    const TYPE_ONE = 1;
    const TYPE_TWO = 2;

    /**
     * 验证基础参数
     * @param $request
     * @return array
     */
    public static function CheckBaseParam($request)
    {
        if (empty($request)) {
            return self::returnError(40201, '未获取到数据');
        }
        if (empty($request['activity_name'])) {
            $msg = '请填写-活动名称';
            return self::returnError(40202, $msg);
        }
        if (strlen($request['activity_name']) > 50) {
            $msg = '活动名称太长';
            return self::returnError(40203, $msg);
        }
        if (empty(strtotime($request['start_time'])) || empty(strtotime($request['end_time']))) {
            $msg = '请选择-活动开始时间及结束时间';
            return self::returnError(40204, $msg);
        }
        if ($request['start_time'] > $request['end_time']) {
            $msg = '结束时间必须大于开始时间';
            return self::returnError(40205, $msg);
        }
        if (empty($request['activity_channels'])) {
            $msg = '请设置-活动渠道';
            return self::returnError(40206, $msg);
        }
        if (empty($request['activity_rules'])) {
            $msg = '请设置-抽奖规则';
            return self::returnError(40207, $msg);
        }
        if (!isset($request['authority'])) {
            $msg = '请设置-抽奖权限';
            return self::returnError(40208, $msg);
        }
        if ($request['authority'] == 1) {
            if (empty($request['only_member_level'])) {
                $msg = '请设置-限定的（会员等级）';
                return self::returnError(40209, $msg);
            }
            if (empty($request['only_distri_level'])) {
                $msg = '请设置-限定的（分销等级）';
                return self::returnError(40210, $msg);
            }
            if (empty($request['nopermission_tip'])) {
                $msg = '请设置-无权限提示语';
                return self::returnError(40211, $msg);
            }
        } else {
            $request['only_member_level'] = '';
            $request['only_distri_level'] = '';
            $request['nopermission_tip'] = '';
        }

        $data = $request;

        //处理参数 活动渠道，会员分级，分销等级
        $data['activity_channels'] = self::arrayToString($request['activity_channels']);
        $data['only_member_level'] = self::arrayToString($request['only_member_level']);
        $data['only_distri_level'] = self::arrayToString($request['only_distri_level']);
        $data['start_time'] = strtotime($request['start_time']);
        $data['end_time'] = strtotime($request['end_time']);

        return self::returnSuccess('ok', $data);

    }

    /**
     * 验证奖品参数
     * @param $request
     * @return array
     */
    public static function CheckBasePrizeParam($request)
    {
        //------------奖品设置
        if (empty($request)) {
            return self::returnError(40221, '未获取到数据');
        }
        if (empty($request['mode']) || !in_array($request['mode'], BigWheelModel::$Lottery_Mode_Type)) {
            $msg = '请选择-抽奖模式';
            return self::returnError(40222, $msg);
        }

        if (empty($request['no_prize_name'])) {
            $msg = '请设置-未中奖名称';
            return self::returnError(40225, $msg);
        }
        if (!isset($request['no_prize_img'])) {
            $msg = '请设置-未中奖图片';
            return self::returnError(40226, $msg);
        }
        if (empty($request['no_prize_tip'])) {
            $msg = '请设置-未中奖提示语';
            return self::returnError(40227, $msg);
        }

        $data = $request;

        return self::returnSuccess('ok', $data);

    }

    /**
     * 验证抽奖次数参数
     * @param $request
     * @return array
     */
    public static function CheckDrawsNumberParam($request)
    {
        //----------抽奖次数
        if (empty($request)) {
            return self::returnError(40231, '未获取到数据');
        }
        if (empty($request['rules_cycle'])) {
            $msg = '请选择--规则周期';
            return self::returnError(40232, $msg);
        }
        if (!isset($request['free_num'])) {
            $msg = '请输入免费获得次数';
            return self::returnError(40233, $msg);
        }
        //额外获取次数规则
        //使用积分换购次数
        $point_rule = ['is_point' => $request['is_point']];
        if (isset($request['is_point']) && $request['is_point'] == 1) {
            if (intval($request['point']) <= 0) {
                $msg = '请输入使用积分';
                return self::returnError(40234, $msg);
            }
            if (!isset($request['point_num']) || !is_numeric($request['point_num'])) {
                $msg = '请输入上限次数';
                return self::returnError(40235, $msg);
            }
            $point_rule['point'] = intval($request['point']);
            $point_rule['num'] = intval($request['point_num']);
        }
        //购买次数
        $buy_rule = ['is_buy' => $request['is_buy']];
        if (isset($request['is_buy']) && $request['is_buy'] == 1) {
            if (floatval($request['buy_money']) <= 0) {
                $msg = '请输入使用金额';
                return self::returnError(40236, $msg);
            }
            if (!isset($request['buy_num']) || !is_numeric($request['buy_num'])) {
                $msg = '请输入上限次数';
                return self::returnError(40237, $msg);
            }
            $buy_rule['money'] = floatval($request['buy_money']);
            $buy_rule['num'] = intval($request['buy_num']);
        }
        //分享获得次数
        $share_rule = ['is_share' => $request['is_share']];
        if (isset($request['is_share']) && $request['is_share'] == 1) {
            if (!isset($request['share_num']) || !is_numeric($request['share_num'])) {
                $msg = '请输入上限次数';
                return self::returnError(40238, $msg);
            }
            $share_rule['num'] = intval($request['share_num']);
        }
        //商城消费获得次数
        $consume_rule = ['is_consume' => $request['is_consume']];
        if (isset($request['is_consume']) && $request['is_consume'] == 1) {
            if (floatval($request['money']) <= 0) {
                $msg = '请输入消费金额';
                return self::returnError(40239, $msg);
            }
            if (!isset($request['consume_num']) || !is_numeric($request['consume_num'])) {
                $msg = '请输入上限次数';
                return self::returnError(40230, $msg);
            }
            $consume_rule['money'] = floatval($request['money']);
            $consume_rule['num'] = intval($request['consume_num']);
        }

        //额外获取参数规则
        $extra_rules = ['point' => $point_rule, 'buy' => $buy_rule, 'share' => $share_rule, 'consume' => $consume_rule];
        $data = [
            'cycle_rules' => $request['rules_cycle'],
            'free_num' => $request['free_num'],
            'extra_rules' => serialize($extra_rules),
        ];
        unset($request);
        return self::returnSuccess('ok', $data);

    }

    /**
     * 验证页面装修参数
     * @param $request
     * @return array
     */
    public static function CheckDecorationParam($request)
    {
        //----------页面装修
        if (empty($request)) {
            return self::returnError(40251, '未获取到数据');
        }
        if (empty($request['page_name'])) {
            $msg = '请填写-页面名称';
            return self::returnError(40252, $msg);
        }
        if (empty($request['top_image'])) {
            $msg = '请上传顶部图片';
            return self::returnError(40253, $msg);
        }
        if (empty($request['background'])) {
            $msg = '请选择背景颜色';
            return self::returnError(40254, $msg);
        }
        if (!isset($request['is_win_list'])) {
            $msg = '请选择中奖名单显示/隐藏';
            return self::returnError(40255, $msg);
        }
        if (empty($request['bottom_text'])) {
            $msg = '请输入底部文字内容';
            return self::returnError(40256, $msg);
        }
        if (empty($request['text_position']) || !in_array($request['text_position'], ['left', 'center', 'right'])) {
            $msg = '请选择文字位置';
            return self::returnError(40257, $msg);
        }
        if (empty($request['text_color'])) {
            $msg = '请选择文字颜色';
            return self::returnError(40258, $msg);
        }
        if (empty($request['button_text'])) {
            $msg = '请输入抽奖按钮内容';
            return self::returnError(40259, $msg);
        }

        return self::returnSuccess('ok', $request);
    }

    /**
     * 验证活动奖品是否符合规定
     * @param $id
     * @param $mode
     * @param $vmin 1:验证最大和最小  0：验证最大值
     * @return array|void
     */
    public function CheckActivityPrizeNum($id, $mode = BigWheelModel::NINE_PALACE_GRID, $vmin = 1)
    {
        $count = BigWheelPrizeModel::getInstance()->getCount(['activity_id' => $id], ['activity_id']);
        if ($vmin && $count < BigWheelModel::$Lottery_Mode[$mode]['min']) {
            $msg = '奖品至少添加' . BigWheelModel::$Lottery_Mode[$mode]['min'] . '个';
            return self::returnError(40224, $msg);
        }
        if ($count > BigWheelModel::$Lottery_Mode[$mode]['max']) {
            $msg = '奖品最多添加' . BigWheelModel::$Lottery_Mode[$mode]['max'] . '个';
            return self::returnError(40224, $msg);
        }
    }

    /**
     * 活动获取次数规则
     * @desc
     * array  point[]          积分使用规则
     * array  point[is_point]  开关
     * array  point[point]     需要积分数
     * array  point[num]       限制兑换次数
     * 积分兑换次数 point    is_point    point  num
     * 购买获得次数 buy      is_buy      money  num
     * 分享获得次数 share    is_share    num
     * 消费获得次数 consume  is_consume  money  num
     * @return void
     */
    public function acticityRules($extra_rules)
    {
        $rule = [];
        if (empty($extra_rules)) {
            return $rule;
        }
        $rule = unserialize($extra_rules);
        return $rule;
    }


    /**
     * 可设置奖品商品列表
     * @param $data
     * @return array
     */
    public function setPrizeGoodsList($data)
    {
        $page = !isset($data['page']) ? 1 : $data['page'];
        $pageSize = !isset($data['pageSize']) ? 5 : $data['pageSize'];

        $condition = [];
        //名称/编码/条形码
        if (isset($data['name']) && !empty($data['name'])) {
            $condition[] = ['title', 'LIKE', '%' . $data['name'] . '%'];
            $condition[] = ['goods_sn', 'LIKE', '%' . $data['name'] . '%', 'or'];
            $condition[] = ['product_sn', 'LIKE', '%' . $data['name'] . '%', 'or'];
        }
        //分类
        if (isset($data['categorys']) && !empty($data['categorys'])) {
            $condition[] = ['categorys', '=', $data['categorys']];
        }
        //分组
        if (isset($data['group']) && !empty($data['group'])) {
            $condition[] = ['group', '=', $data['group']];
        }
        //类型
        if (isset($data['type']) && !empty($data['type'])) {
            $condition[] = ['type', '=', $data['type']];
        }
        //状态
        if (isset($data['status'])) {
            $condition[] = ['status', '=', $data['status']];
        }

        //列表  商品图片  商品名称 价格  库存 商品类型  商品状态
        $field = ['id', 'title', 'thumb', 'thumb_url', 'price', 'stock', 'real_sales', 'created_at'];
        $list = GoodsModel::listed($page, $pageSize, $condition, [], $field);
        return $list;
    }

    /**
     * 可设置奖品优惠券列表
     * @param $data
     * @return array
     */
    public function setPrizeCouponList($data)
    {
        $page = !isset($data['page']) ? 1 : $data['page'];
        $pageSize = !isset($data['pageSize']) ? 5 : $data['pageSize'];
        //默认展示通用券
        $type = !isset($data['type']) ? 1 : $data['type'];

        $condition = [];
        $condition[] = ['is_deleted', '=', 0];
        if (isset($data['name']) && !empty($data['name'])) {
            $condition[] = ['name', 'LIKE', '%' . $data['name'] . '%'];
        }
        //1 通用券  2 专用券
        $condition[] = ['type', '=', $type];
        //列表
        $select = ['id', 'name', 'city', 'coupon_type', 'category', 'shop_id', 'remitted_money', 'subsidy_type', 'subsidy_money', 'use_time_start', 'use_time_end', 'created_at', 'stock'];
        $list = Coupon::listed($page, $pageSize, $condition, $select);
        return $list;
    }

    /**
     * 活动列表数据
     * @param $activity_id
     * @return array
     */
    public function getActivityList($data)
    {
        $page = !isset($data['page']) ? 1 : $data['page'];
        $pageSize = !isset($data['pageSize']) ? 5 : $data['pageSize'];

        $condition = [];
        if (isset($data['name']) && !empty($data['name'])) {
            $condition[] = ['activity_name', 'LIKE', '%' . $data['name'] . '%'];
        }
        if (isset($data['status'])) {
            $condition[] = ['status', '=', $data['status']];
        }
        //列表
        $list = BigWheelModel::getInstance()->getList($condition, $page, $pageSize);

        return $list;
    }

    /**
     * 活动--抽奖记录
     * @param $data
     * @return array
     */
    public function getPrizeRecordList($data)
    {
        $page = !isset($data['page']) ? 1 : $data['page'];
        $pageSize = !isset($data['pageSize']) ? 5 : $data['pageSize'];

        $condition = [];
        $condition['activity_id'] = $data['activity_id'];
        if (isset($data['name']) && !empty($data['name'])) {
            $condition[] = ['name', 'LIKE', '%' . $data['name'] . '%'];
        }
        if (isset($data['status'])) {
            $condition[] = ['status', '=', $data['status']];
        }
        if (isset($data['start_time']) && !empty($data['start_time'])) {
            $condition[] = ['create_time', '>=', strtotime($data['start_time'])];
        }
        if (isset($data['end_time']) && !empty($data['end_time'])) {
            $condition[] = ['create_time', '<=', strtotime($data['end_time'])];
        }

        //列表
        $list = BigWheelLogModel::getInstance()->getList($condition, $page, $pageSize);
        if (!empty($list['data'])) {
            $member_ids = array_column($list['data'], 'uid');
            $field = ['uid', 'avatar', 'nickname', 'mobile'];
            $member_list = Member::getInstance()->getMemberList([], ['uid' => $member_ids], $field);
            $member_list = array_column($member_list, null, 'uid');
            //增加用户数据
            foreach ($list['data'] as &$val) {
                $val->info = isset($member_list[$val->uid]) ? $member_list[$val->uid] : [];
                $val->create_time = getFormatTime($val->create_time);
            }
        }
//        echo "<pre>";
//        print_r($list);
//        die;
        return $list;
    }

    /**
     * 活动详情
     * @param $activity_id
     * @return array
     */
    public function getActivityInfo($activity_id)
    {
        //详情
        $info = BigWheelModel::getInstance()->getInfo(['activity_id' => $activity_id]);
        if (!empty($info)) {
            //时间戳处理
            $info->start_time = date('Y-m-d', $info->start_time);
            $info->end_time = date('Y-m-d', $info->end_time);
            //活动渠道处理
            //活动规则处理 --extra_rules 反序列化
        }
        return $info;
    }

    /**
     * 删除活动
     * @param $activity_id
     * @return array
     */
    public function deleteActivityData($activity_id)
    {
        if (!self::activityExists($activity_id)) {
            return self::returnError(40226, '数据不存在');
        }

        //删除
        $res = BigWheelModel::getInstance()->deleteData(['activity_id' => $activity_id]);
        if ($res['status']) {
            return self::returnSuccess('ok');
        } else {
            return self::returnError(40227, '删除失败');
        }
    }

    /**
     * 验证活动数据是否存在
     * @param $id
     * @return array
     */
    public function activityExists($id)
    {
        $info = BigWheelModel::getInstance()->getInfo(['activity_id' => $id], ['activity_id']);
        return $info;
    }


    /**
     * 活动数据更新
     * @param $id  活动id
     * @param $data 数据
     * @return int|string
     */
    public function activityDataSave($id, $data)
    {
        $result = [];
        if (empty($id) || empty($data) || !is_array($data)) {
            return $result;
        }
        $condition = ['activity_id' => $id];
        $result = BigWheelModel::getInstance()->updateSave($condition, $data);
        return $result;
    }

    /**
     * 将数组转换成字符串
     * @param $array
     * @return string|void
     */
    public function arrayToString($array)
    {
        $string = '';
        if (empty($array) || !is_array($array)) {
            return $string;
        }
        return implode(',', $array);
    }


    /**
     * 保存参与记录
     */
    public static function SaveLog()
    {


    }



    /**
     * 大转盘抽奖逻辑
     * @return void
     */
    public function goLottery($activity_id)
    {
        $uid = 9;
        $field = ['activity_id', 'start_time', 'end_time', 'cycle_rules', 'free_num', 'extra_rules'];
//        $field = ['*'];
        $activity_info = BigWheelModel::getInstance()->getInfo(['activity_id' => $activity_id], $field);
        if (empty($activity_info)) {
            return $activity_info;
        }
        $activity_info = json_decode(json_encode($activity_info), true);
        /**
         * 抽奖权限  未开发
         * 根据用户等级，分销等级进行限制
         * 用户等级，分销等级
         */
        //获取用户抽奖次数
        $num = LotteryServices::getNumByLotteryRules($activity_info, $uid);

        //获取用户抽奖次数
        if ($num > 0) {
            //次数抽奖流程
            $result = LotteryServices::numLottery($activity_info, $uid);
            if ($result['status'] != 0) {
                return self::returnError($result['status'], $result['msg']);
            }
        } else {
            //积分抽奖流程
            $result = LotteryServices::pointLottery($activity_info, $uid);
            if ($result['status'] != 0) {
                return self::returnError($result['status'], $result['msg']);
            }

        }
        //重新整理返回参数
        $data = [];
        $data['prize']= $result['data']['pid'];
        $data['desc']= $result['data']['name'];
        unset($result);
        return self::returnSuccess('ok', $data);
    }

    /**
     * 获取用户抽奖次数
     * @return void
     */
    public function getUserLotteryNum($activity_id,$uid)
    {
        if(empty($activity_id)||empty($uid)){
            return self::returnError(402005, '未获取到登录信息');
        }
        $field = ['activity_id', 'start_time', 'end_time', 'cycle_rules', 'free_num', 'extra_rules'];
//        $field = ['*'];
        $activity_info = BigWheelModel::getInstance()->getInfo(['activity_id' => $activity_id], $field);
        if (empty($activity_info)) {
            return self::returnError(402006, '活动不存在');
        }
        $activity_info = json_decode(json_encode($activity_info), true);
//        $activity_info = objectToArray();
        /**
         * 抽奖权限  未开发
         * 根据用户等级，分销等级进行限制
         * 用户等级，分销等级
         */
        //获取用户抽奖次数
        $num = LotteryServices::getNumByLotteryRules($activity_info, $uid);
        return self::returnSuccess('ok', $num);
    }





}
